import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_learn_vi/src/bean/bean_problem.dart';
import 'package:flutter_learn_vi/src/page/bloc/model_wrong_question.dart';
import 'package:flutter_learn_vi/src/page/topic/data/count_model.dart';
import 'package:flutter_learn_vi/src/page/topic/data/topic_text_model.dart';
import 'package:flutter_learn_vi/src/page/topic/topic_enum.dart';
import 'package:flutter_learn_vi/src/utils/log_util.dart';
import 'package:flutter_learn_vi/src/utils/string_utils.dart';
import 'package:provider/provider.dart';

import '../../net/dio_utils.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2020/12/13.
///
/// 可关注公众号：我的大前端生涯   获取最新技术分享
/// 可关注网易云课堂：https://study.163.com/instructor/1021406098.htm
/// 可关注博客：https://blog.csdn.net/zl18603543572
///
/// 代码清单
/// 单选题、判断题 、多选题
class TopicSingleWidget extends StatefulWidget {
  final ProblemModel problemModel;

  //是否是多选
  final bool isMul;

  //选择后是否自动显示答案 错题再练使用
  final bool isMyError;

  ///答题类型
  final TopicEnum topicEnum;
  final bool isUpdateError;

  TopicSingleWidget(
    this.problemModel, {
    @required this.topicEnum,
    this.isMul = false,
    this.isMyError = false,
    this.isUpdateError,
  });

  @override
  _TopicSingleWidgetState createState() => _TopicSingleWidgetState();
}

class _TopicSingleWidgetState extends State<TopicSingleWidget> with WrongModel {
  @override
  void initState() {
    super.initState();
    _showAnswerMessage = widget.problemModel.showAnswerMessage;
  }

  @override
  Widget build(BuildContext context) {
    List<Widget> itemList = [];
    String options = widget.problemModel.options;
    var pareOptions = jsonDecode(options);
    String themAnswerStr = widget.problemModel.themAnswerStr;
    List stringList = ["A", "B", "C", "D", "E", "F", "G", "H"];
    if (pareOptions is List) {
      for (int i = 0; i < pareOptions.length; i++) {
        String index = stringList[i];

        Color selectColor = Colors.grey;
        Color indexColor = Colors.black;
        Color titleColor = Colors.black;
        FontWeight fontWeight = FontWeight.normal;
        if (themAnswerStr != null && themAnswerStr.contains(index)) {
          selectColor = Colors.blue;
          indexColor = Colors.white;
          titleColor = Colors.blue;
          fontWeight = FontWeight.w700;
        }

        Widget row = Consumer<TopicTextModel>(
          builder: (BuildContext context, TopicTextModel model, Widget child) {
            return Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  alignment: Alignment.center,
                  margin: EdgeInsets.only(right: 10),
                  height: 24,
                  width: 24,
                  decoration: BoxDecoration(
                      color: selectColor,
                      borderRadius: BorderRadius.all(Radius.circular(20))),
                  child: Text(
                    index,
                    style: TextStyle(
                        fontWeight: fontWeight,
                        color: indexColor,
                        fontSize: model.textSizeBean.itemSize),
                  ),
                ),
                Expanded(
                  child: Text(
                    pareOptions[i]
                        .replaceAll("<p>", "")
                        .replaceAll("<\/p>", ""),
                    style: TextStyle(
                        fontWeight: fontWeight,
                        color: titleColor,
                        fontSize: model.textSizeBean.itemSize),
                  ),
                ),
              ],
            );
          },
        );

        Container container = Container(
          child: row,
          margin: EdgeInsets.only(top: 6, bottom: 6),
        );

        InkWell inkWell = InkWell(
          onTap: () {
            if (!StringUtils.isEmpty(_showAnswerMessage)) {
              return;
            }
            if (widget.isMul) {
              if (widget.problemModel.themAnswerStr == null) {
                widget.problemModel.themAnswerStr = index;
              } else {
                if (widget.problemModel.themAnswerStr.contains(index)) {
                  widget.problemModel.themAnswerStr =
                      widget.problemModel.themAnswerStr.replaceAll(index, "");
                } else {
                  widget.problemModel.themAnswerStr += index;
                }
              }
            } else {
              widget.problemModel.themAnswerStr = index;
            }
            //多选的时候不需要实时
            if (widget.isMyError && !widget.isMul) {
              checkRightAnswer();
            }

            setState(() {});
          },
          child: container,
        );

        itemList.add(inkWell);
      }
    }

    if (_showAnswerMessage != null) {
      Color color = Colors.green;
      if (_showAnswerMessage.contains("回答错误")) {
        color = Colors.redAccent;
      }
      itemList.add(Text(
        "$_showAnswerMessage",
        style: TextStyle(color: color),
      ));
    } else if (widget.isMul && widget.isMyError) {
      //如果是多选 并且是练习错题 就显示提交按钮
      itemList.add(ElevatedButton(
        child: Text("提交答案"),
        onPressed: () {
          checkRightAnswer();
          setState(() {});
        },
      ));
    }
    LogUtils.e("$pareOptions");
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: itemList,
    );
  }

  String _showAnswerMessage;

  //检查正确答案
  void checkRightAnswer() async {
    _showAnswerMessage = checkQuestionFunction(widget.problemModel);

    if (widget.topicEnum == TopicEnum.myError) {
      if (_showAnswerMessage == "回答正确") {
        LogUtils.e("回答正确 ${widget.problemModel.id}");
        //修改回答正确的次数
        await updateUserWrongTimes(widget.problemModel.id);
      }
    }
    widget.problemModel.showAnswerMessage = _showAnswerMessage;
    context.read<CountModel>().check();
  }

  Future<bool> updateUserWrongTimes(int id) async {
    Map<String, dynamic> map2 = {};

    ResponseInfo responseInfo = await DioUtils.instance.getRequest(
        url: HttpHelper.pdateCountError + "$id", queryParameters: map2);
    if (responseInfo.success) {
      if (responseInfo.data != null) {
        //解析数据
        _showAnswerMessage = _showAnswerMessage + "【" + responseInfo.data + "】";
      }
    } else {}

    return true;
  }
}
